<template>
    <div class="app-container">
        <div class="filler-container">
            <el-input v-model="listQuery.options.id.fieldValue" placeholder="主键" style="width: 200px;"
                      class="filter-item"
                      @keyup.enter.native="handleFilter"/>
            <el-date-picker
                    v-model="listQuery.options.createTime.fieldValue"
                    type="datetime"
                    placeholder="创建开始时间">
            </el-date-picker>
            <el-date-picker
                    v-model="listQuery.options.createTime.fieldValueTwo"
                    type="datetime"
                    placeholder="创建结束时间">
            </el-date-picker>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item"
                       style="margin-left: 10px;"
                       type="primary"
                       icon="el-icon-edit"
                       @click="handleCreate">
                添加
            </el-button>
            <el-button class="filter-item"
                       style="margin-left: 10px;"
                       type="primary"
                       icon="el-icon-edit"
                       @click="batchHandleDelete">
                删除选中项
            </el-button>
            <el-button  v-waves
                        :loading="downloadLoading"
                        class="filter-item"
                        type="primary"
                        icon="el-icon-download"
                        @click="handleDownload">
                导出
            </el-button>
        </div>
        <div class="filter-container">
        </div>

        <el-table :key="tableKey"
                    v-loading="listLoading"
                    :data="list"
                    border
                    fit
                    highlight-current-row
                    style="width: 100%;"
                    @selection-change="handleSelectionChange"
                    @sort-change="sortChange">
            <el-table-column type="selection" width="55"/>
        <#list table.commonFields as field>
            <el-table-column label="${(field.comment??  && field.comment != "")?string(field.comment,field.propertyName)}" prop="${field.name}" align="center" width="80" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{ scope.row.${field.propertyName} }}</span>
                </template>
            </el-table-column>
        </#list>
        <#list table.fields as field>
            <el-table-column label="${(field.comment??  && field.comment != "")?string(field.comment,field.propertyName)}" prop="${field.name}" align="center" width="80" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{ scope.row.${field.propertyName} }}</span>
                </template>
            </el-table-column>
        </#list>
            <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        修改
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0"
                :total="total"
                :page.sync="listQuery.page"
                :limit.sync="listQuery.size"
                @pagination="getList"/>

        <el-dialog :title="this.dialogAddFormTitle" :visible.sync="dialogAddFormVisible">
            <el-form ref="addDataForm"
                    :rules="rules"
                    :model="temp"
                    label-position="left"
                    label-width="120px"
                    style="width: 400px; margin-left:50px;">
            <#list table.commonFields as field>
                <el-form-item label="${(field.comment??  && field.comment != "")?string(field.comment,field.propertyName)}" prop="${field.propertyName}">
                    <el-input v-model="temp.${field.propertyName}"/>
                </el-form-item>
            </#list>
            <#list table.fields as field>
                <el-form-item label="${(field.comment??  && field.comment != "")?string(field.comment,field.propertyName)}" prop="${field.propertyName}">
                    <el-input v-model="temp.${field.propertyName}"/>
                </el-form-item>
            </#list>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="createData()">
                    提交
                </el-button>
            </div>
        </el-dialog>

        <el-dialog :title="this.dialogEditFormTitle" :visible.sync="dialogEditFormVisible">
            <el-form ref="editDataForm"
                    :rules="rules"
                    :model="temp"
                    label-position="left"
                    label-width="120px"
                    style="width: 400px; margin-left:50px;">
            <#list table.commonFields as field>
                <el-form-item label="${(field.comment??  && field.comment != "")?string(field.comment,field.propertyName)}" prop="${field.propertyName}">
                    <el-input v-model="temp.${field.propertyName}"/>
                </el-form-item>
            </#list>
            <#list table.fields as field>
                <el-form-item label="${(field.comment??  && field.comment != "")?string(field.comment,field.propertyName)}" prop="${field.propertyName}">
                    <el-input v-model="temp.${field.propertyName}"/>
                </el-form-item>
            </#list>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="updateData()">
                    提交
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    <#assign  myPath = entity ? uncap_first>
    import { getPage, createEntity, updateEntity, deleteEntity } from '@/api/${myPath}'
    import waves from '@/directive/waves' // waves directive
    import { parseTime } from '@/utils'
    import Pagination from '@/components/Pagination' // secondary package based on el-pagination
    import DictSelect from '@/components/DictSelect'
    import DictSpan from '@/components/DictSpan'

    export default {
        name: 'Menu',
        components: {Pagination, DictSelect, DictSpan},
        directives: {waves},
        data() {
            return {
                tableKey: 0,
                list: null,
                rules: {},
                total: 0,
                listLoading: true,
                listQuery: {
                    page: 1,
                    size: 20,
                    orderType: 2,
                    orderColumn: 'create_time',
                    options: {
                        id: {
                            optionType: 'EQ',
                            fieldType: 'LONG',
                            fieldName: 'id',
                            fieldValue: null,
                            fieldValueTwo: null
                        },
                        createTime: {
                            optionType: 'BETWEEN',
                            fieldType: 'PICKER_DATE_TO_lONG',
                            fieldName: 'create_time',
                            fieldValue: null,
                            fieldValueTwo: null
                        }
                    }
                },
                multipleSelection: [],
                sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
                showReviewer: false,
                temp: {
            <#list table.commonFields as field>
                    ${field.propertyName}: null,
            </#list>
            <#list table.fields as field>
                    ${field.propertyName}:null<#if field_has_next>,</#if>
            </#list>
                 },
                dialogAddFormTitle:  '添加',
                dialogAddFormVisible: false,
                dialogEditFormTitle: '编辑',
                dialogEditFormVisible: false,
                downloadLoading: false
            }
        },
        created() {
            this.getList()
        },
        methods: {
            getList() {
                this.listLoading = true
                getPage(this.listQuery).then(response => {
                    this.list = response.data.records
                    this.total = response.data.total
                    // Just to simulate the time of the request
                    setTimeout(() => {
                        this.listLoading = false
                    }, 500)
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            sortChange(data) {
                const { prop, order } = data
                if (order) {
                    if (order === 'ascending') {
                        this.listQuery.orderType = 1
                    } else {
                        this.listQuery.orderType = 2
                    }
                    this.listQuery.orderColumn = prop
                    this.handleFilter()
                }
            },
            resetTemp() {
                this.temp = {
                <#list table.commonFields as field>
                    ${field.propertyName}:null,
                </#list>
                <#list table.fields as field>
                    ${field.propertyName}:null<#if field_has_next>,</#if>
                </#list>
            }
            },
            handleCreate() {
                this.resetTemp()
                this.dialogAddFormVisible = true
                this.$nextTick(() => {
                    this.$refs['addDataForm'].clearValidate()
                })
            },
            createData() {
                this.$refs['addDataForm'].validate((valid) => {
                    if (valid) {
                        createEntity(this.temp).then(response => {
                            this.list.unshift(response.data)
                            this.dialogAddFormVisible = false
                            this.$notify({
                                title: '提示',
                                message: '添加成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                    }
                })
            },
            handleUpdate(row) {
                this.temp = Object.assign({}, row) // copy obj
                this.dialogEditFormVisible = true
                this.$nextTick(() => {
                    this.$refs['editDataForm'].clearValidate()
                })
            },
            updateRow(row) {
                const tempData = Object.assign({}, row)
                updateEntity(tempData).then(response => {
                    for (const v of this.list) {
                        if (v.id === this.temp.id) {
                            const index = this.list.indexOf(v)
                            this.list.splice(index, 1, response.data)
                            break
                        }
                    }
                    this.dialogEditFormVisible = false
                    this.$notify({
                        title: '提示',
                        message: '修改成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            updateData() {
                this.$refs['editDataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)
                        updateEntity(tempData).then(response => {
                            for (const v of this.list) {
                                if (v.id === this.temp.id) {
                                    const index = this.list.indexOf(v)
                                    this.list.splice(index, 1, response.data)
                                    break
                                }
                            }
                            this.dialogEditFormVisible = false
                            this.$notify({
                                title: '提示',
                                message: '修改成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                    }
                })
            },
            handleDelete(row) {
                const ids = []
                ids.push(row.id)
                deleteEntity(ids).then(res => {
                    this.$notify({
                        title: '提示',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                    const index = this.list.indexOf(row)
                    this.list.splice(index, 1)
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            batchHandleDelete() {
                const length = this.multipleSelection.length
                const ids = []
                for (let i = 0; i < length; i++) {
                    ids.push(this.multipleSelection[i].id)
                }
                deleteEntity(ids).then(res => {
                    this.$notify({
                        title: '提示',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                    for (let i = 0; i < length; i++) {
                        const index = this.list.indexOf(this.multipleSelection[i])
                        this.list.splice(index, 1)
                    }
                })
                this.multipleSelection = []
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = []
                    <#list table.commonFields as field>
                    tHeader.push('${field.propertyName}')
                    </#list>
                    <#list table.fields as field>
                    tHeader.push('${field.propertyName}')
                    </#list>
                    const filterVal = []
                    <#list table.commonFields as field>
                    filterVal.push('${field.propertyName}')
                    </#list>
                    <#list table.fields as field>
                    filterVal.push('${field.propertyName}')
                    </#list>
                    const data = this.formatJson(filterVal, this.list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: '${entity}'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    if (j === 'timestamp') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                }))
            }
        }
    }
</script>

